<?php

namespace app\common\services;

use api\sms\exception\SmsException;
use api\sms\Sms;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

class MailerService
{

    protected PHPMailer $mail;

    /**
     * @param int $itemsId 企业ID
     * @throws Exception
     */
    public function __construct(int $itemsId = 0)
    {
        // 邮箱配置
        $mailConfig = web_config($itemsId, 'program.mail');

        //Create an instance; passing `true` enables exceptions
        $this->mail = new PHPMailer(true);

        //Server settings
        $this->mail->SMTPDebug = SMTP::DEBUG_OFF;                      //Enable verbose debug output
        $this->mail->CharSet = PHPMailer::CHARSET_UTF8; // 设置文字编码
        $this->mail->isSMTP();                                            //Send using SMTP
        $this->mail->Host = $mailConfig['host'];                     //Set the SMTP server to send through
        $this->mail->SMTPAuth = true;                                   //Enable SMTP authentication
        $this->mail->Username = $mailConfig['send_email'];                     //SMTP username
        $this->mail->Password = $mailConfig['password'];                               //SMTP password
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $this->mail->Port = $mailConfig['port'] ?? 465;

        $this->mail->setFrom($mailConfig['send_email'], $mailConfig['send_nickname']); // 设置发信人

        if (isset($mailConfig['reply_email']) && $mailConfig['reply_email'] && isset($mailConfig['reply_nickname']) && $mailConfig['reply_nickname']) {
            $this->mail->addReplyTo($mailConfig['reply_email'], $mailConfig['reply_nickname']); // 设置回复人信息
        }
    }

    public function sendMail($recipient, string $subject, string $body, $annex = null, array $ccTos = [], array $bccTos = [])
    {
        try {                             //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
            //Recipients
            if (is_array($recipient)) {
                if (isset($recipient[0])) {
                    foreach ($recipient as $k => $v) {
                        $this->mail->addAddress($k, $v);
                    }
                } else {
                    $this->mail->addAddress($recipient['email'], $recipient['nickname'] ?? '');
                }
            } else {
                $this->mail->addAddress($recipient);               //Name is optional
            }

            if ($ccTos) {
                foreach ($ccTos as $v) {
                    $this->mail->addCC($v); // 添加抄送人
                }
            }

            if ($bccTos) {
                foreach ($bccTos as $v) {
                    $this->mail->addBCC($v); // 添加暗抄送人
                }
            }

            if ($annex) {
                if (is_array($annex)) {
                    if (isset($annex[0])) {
                        foreach ($annex as $k => $v) {
                            $this->mail->addAttachment($k, $v);
                        }
                    } else {
                        $this->mail->addAttachment($annex['file_path'], $annex['file_name'] ?? '');
                    }
                } else {
                    $this->mail->addAttachment($annex); // 添加附件信息
                }
            }

            //Content
            $this->mail->isHTML(true); //Set email format to HTML
            $this->mail->Subject = $subject;
            $this->mail->Body = $body;
//            $this->mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            return $this->mail->send();
        } catch (Exception $e) {
            exception_log('邮件发送失败', $e);
        }
    }

    /**
     * 初始化
     * @param int $itemsId 企业ID
     * @return MailerService
     */
    public static function init(int $itemsId = 0)
    {

        return new self($itemsId);
    }

    public function __call($name, $arguments)
    {
        return $this->mail->$name(...$arguments);
    }

}